/*
3、司机售票员问题
	创建子进程代表售票员，父进程代表司机 ，同步过程如下：

	售票员捕捉SIGINT(代表开车)，发SIGUSR1给司机，司机打印(“let’s gogogo”)
	售票员捕捉SIGQUIT(代表停车)，发SIGUSR2给司机，司机打印(“stop the bus”)
	司机捕捉SIGTSTP(代表车到总站)，发SIGUSR1给售票员，售票员打印(“please get off the bus”)
*/


#include <stdlib.h>
#include <stdio.h>
#include <signal.h>
#include <unistd.h>


pid_t seller;
pid_t driver;

void seller_handler(int signum)
{
	switch(signum)
	{
	case SIGINT:
		kill(driver, SIGUSR1);
		break;
	case SIGQUIT:
		kill(driver, SIGUSR2);
		break;
	case SIGUSR1:
		printf("seller : please get off the bus\n");
		break;
	default:
		printf("seller : SIG is not supported\n");
	}
}

void driver_handler(int signum)
{
	switch(signum)
	{
	case SIGUSR1:
		printf("driver : let's go go go!\n");
		break;
	case SIGUSR2:
		printf("driver : stop the bus!\n");
		break;
	case SIGTSTP:
		kill(seller, SIGUSR1);
		break;
	default:
		printf("driver : SIG is not supported\n");
	}
}


int main()
{
	driver = getpid();

	signal(SIGINT, SIG_IGN);//ctrl + c
	signal(SIGTSTP, SIG_IGN);//ctrl + z
	signal(SIGQUIT, SIG_IGN);//ctrl + \

	seller = fork();

	if(seller == -1)
		perror("fork failed");
	else if(seller == 0)
	{
		seller = getpid();
		printf("This is seller : %d\n", seller);
		signal(SIGINT,seller_handler);
		signal(SIGQUIT, seller_handler);
		signal(SIGUSR1, seller_handler);
		while(1);
	}
	else
	{
		driver = getpid();
		printf("This is driver : %d\n", driver);
		signal(SIGTSTP, driver_handler);
		signal(SIGUSR1, driver_handler);
		signal(SIGUSR2, driver_handler);
		while(1);
	}
	
}
